--mgrs.gameState:init("log/tmp1.dat");
--mgrs.gameState:init("log/tmp2.dat");
--mgrs.gameState:addValue("log/tmp1.dat","key11","aaaa");
--mgrs.gameState:addValue("log/tmp2.dat","key22","bbbb");
--mgrs.gameState:saveByFileName("log/tmp1.dat");
--mgrs.gameState:saveByFileName("log/tmp2.dat");
--mgrs.log:printDebug(mgrs.gameState:getVale("log/tmp1.dat","key11"));
--mgrs.log:printDebug(mgrs.gameState:getVale("log/tmp2.dat","key22"));
local FileData = class("FileData");
function FileData:ctor(fileName,secretKey)
    self.fileName = fileName or "tmp_" .. os.time() .. ".dat";
    self.secretKey = secretKey or "secretKey";
    self.fileData = {};
end

local gameState = require(SCRIPTS_DIR .. ".pubs.GameState");
local GameStateMgr = class("GameStateMgr");
function GameStateMgr:ctor()
    self.fileObjects = {};
    self.secretKey = "secretKey";
end

function GameStateMgr:stateListener(event)
    if event.errorCode then
		mgrs.log:printNotice("ERROR, load:" .. event.errorCode);
		return
	end
    local returnValue = nil;
    if "load" == event.name then
        local str = event.values.data
		local str = crypto.decryptXXTEA(str, self.secretKey);
        returnValue = json.decode(str);
    elseif "save" == event.name then
        local str = json.encode(event.values);
        str = crypto.encryptXXTEA(str, self.secretKey);
        returnValue = {data = str};
	end
    return returnValue;
end


function GameStateMgr:init(fileName,secretKey)
    self.secretKey = secretKey;
    local fileObj = FileData.new(fileName,secretKey);
	gameState.init(handler(self,self.stateListener));
    fileObj.fileData = gameState.load(fileObj.fileName,fileObj.secretKey) or {};
    self.fileObjects[fileName] = fileObj
    return fileObj;
end

function GameStateMgr:getValue(fileName,name)
    local fileObj = self.fileObjects[fileName];
    if fileObj then
        local fileData = fileObj.fileData;
        return fileData[name];
    end
    return nil;
end

function GameStateMgr:addValue(fileName,name,value)
    local fileObj = self.fileObjects[fileName];
    if fileObj then
        fileObj.fileData[name] = value;
    end
end

function GameStateMgr:saveByObject(fileObj)
    if fileObj then
        gameState.save(fileObj.fileName,fileObj.fileData,fileObj.secretKey);
    end
end

function GameStateMgr:saveByFileName(fileName)
    local fileObj = self.fileObjects[fileName];
    self:saveByObject(fileObj)
end

mgrs.gameState = nil;
mgrs.singleClass(mgrs,GameStateMgr,"gameState");

--endregion
